<?php

namespace App\Http\Controllers\Backstage\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
//后台登录模块
class LoginController extends Controller
{
    public function login(Request $request)
    {
        $appid = '';
        $appsecret = 'VXyZ50Dc$^jNvIFt';
        $name =  $request->input('name');
        $password = $request->input('password');
        $publicKey = $request->input('publicKey');
        $private_key = Cache::get($publicKey);
        //传输的加密密码解密
        openssl_private_decrypt(base64_decode($password), $decrypted, $private_key);
        $password = $decrypted;
        Cache::put($publicKey, $private_key, 0);
        $info = DB::table('admin')->where('name', $name)->first();
        $ip = get_real_ip();
        if (!Cache::has($ip . '_login')) {
            Cache::put($ip . '_login', 1, 3600);
        }
        //防止暴力破解
        if (Cache::get($ip . '_login') > 9) {
            $data = fail();
            $data['msg'] = '账号禁止登录';
            return $data;
        }
        if ($info) {
            //验证密码
            if (Hash::check($password, $info->password)) {
                $datainfo['aid'] = $info->aid;
                $datainfo['name'] = $info->name;
                $datainfo['merchant_id'] = $info->merchant_id;
                // $datainfo['category']=$info->category;
                $data = success();
                //生产token
                $appid = $datainfo['aid'] . 'admin';
                $ori_str = Cache::get($appid . '_' . $appsecret);
                if (!$ori_str) {
                    //重新获取就把以前的token删除
                    Cache::forget($ori_str);
                    //这里是token产生的机制
                    $nonce = $this->createNoncestr(32);
                    $tmpArr = array($nonce, $appid, $appsecret);
                    sort($tmpArr, SORT_STRING);
                    $tmpStr = implode($tmpArr);
                    $tmpStr = sha1($tmpStr);
                    Cache::put($appid . '_' . $appsecret, $tmpStr, 7200);
                    Cache::put($tmpStr, $appid . '_' . $appsecret, 7200);
                    $data['token'] = $tmpStr;
                    //这里做了缓存 'a'=>b 和'b'=>a格式的缓存
                } else {
                    $data['token'] = $ori_str;
                }
                $data['data'] = $datainfo;
                return $data;
            } else {
                $num = Cache::get($ip . '_login');
                Cache::put($ip . '_login', $num + 1, 3600);
                $data = fail();
                $data['msg'] = '密码错误，请重试';
                return $data;
            }
        } else {
            $num = Cache::get($ip . '_login');
            Cache::put($ip . '_login', $num + 1, 3600);
            $data = fail();
            $data['msg'] = '密码错误，请重试';
            return $data;
        }
    }

    /**
     *  作用：产生随机字符串，不长于32位
     */
    function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //生成密钥
    public function getpubKey()
    {
        $config = array(
            "digest_alg" => "sha512",
            "private_key_bits" => 2048,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
            // 'config' => $opensslConfigPath
        );
        //创建密钥对
        $res = openssl_pkey_new($config);
        //生成私钥
        openssl_pkey_export($res, $privkey);
        //生成公钥
        $pubKey = openssl_pkey_get_details($res)['key'];
        $pubKey = str_replace("-----BEGIN PUBLIC KEY-----", "", $pubKey);
        $pubKey = str_replace("-----END PUBLIC KEY-----", "", $pubKey);
        $pubKey = str_replace("\n", "", $pubKey);
        $data = success();
        // $data['privkey'] = $privkey;
        $data['pubKey'] = $pubKey;
        Cache::put($pubKey, $privkey, 7200);
        return $data;
    }

    // public function test()
    // {
    //     $pwd = Crypt::encryptString('123456');
    //     return $pwd;
    // }
}
